package com.cloudfun.campusshare.schedule;

import cn.hutool.core.date.DateUtil;
import com.cloudfun.campusshare.common.model.dto.dingtalk.TextContent;
import com.cloudfun.campusshare.dao.DeviceDao;
import com.cloudfun.campusshare.entity.DeviceEntity;
import com.cloudfun.campusshare.entity.UserEntity;
import com.cloudfun.campusshare.repo.DeviceEntityRepo;
import com.cloudfun.campusshare.repo.UserEntityRepo;
import com.cloudfun.campusshare.service.DeviceService;
import com.cloudfun.campusshare.service.DingTalkService;
import com.cloudfun.campusshare.util.tencent.TencentSMSUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;

/**
 * @author wangxiyuan
 * @description 设备离线预警
 * @createDate 2021/7/8 11:40
 **/
@Slf4j
@Component
public class OfflineWarning {
    @Autowired
    private DeviceEntityRepo deviceEntityRepo;
    @Autowired
    private UserEntityRepo userEntityRepo;

    @Autowired
    private DingTalkService dingTalkService;
    // 每半个小时统计一次
    @Scheduled(cron = "0 0/30 * * * ?")
    public void offlineWarning() {
        List<DeviceEntity> allUsingOfflineDevice = deviceEntityRepo.findAllUsingOfflineDevice();
        Map<String,StringBuilder> map = new WeakHashMap<>();
        // 收集离线超过一定时长的设备Imei
        if(CollectionUtils.isNotEmpty(allUsingOfflineDevice)){
            allUsingOfflineDevice.forEach(d ->{
                // 如果离线时间距离上次交互超过 30min，将发短信通知预警
                long endTime = LocalDateTime.now().minusMinutes(30).toInstant(ZoneOffset.of("+8")).toEpochMilli();
                if(endTime > Long.parseLong(d.getLastInteractionTime())){
                    if(map.get(d.getUserId()) != null){
                        map.put(d.getUserId(),map.get(d.getUserId()).append(d.getImei()).append(","));
                    }else{
                        map.put(d.getUserId(),new StringBuilder(d.getImei()));
                    }
                }
            });
        }
        for (String userId : map.keySet()) {
            StringBuilder stringBuilder = map.get(userId);
            // 发短信通知运营商
            Optional<UserEntity> byId = userEntityRepo.findById(userId);
            if(byId.isPresent()){
                UserEntity userEntity = byId.get();
                // 测试只允许向17600884246 发送消息
                if(StringUtils.isNotBlank(userEntity.getPhone()) && userEntity.getEnable()){
                    log.info("有效用户手机号为{}",userEntity.getPhone());
                    TextContent textContent = new TextContent("离线已经超过30min的设备有" + stringBuilder.toString());
                    dingTalkService.sendMessage(textContent);
                    // 配置短信模板
                    try {
                        TencentSMSUtil.sendSMSWithParams(userEntity.getPhone(), 0, new String[]{stringBuilder.toString()});
                    } catch (IOException e) {
                        log.error("设备离线提醒短信发送失败,失败原因[}",e);
                    }
                }
            }
        }
    }

    public static void main(String[] args) {

        HashMap<Object, Object> map = new HashMap<>();
        map.put(null,null);
    }

}
